﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Mahasiswa.WP.Resources;
using Mahasiswa.WP.ViewModels;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

using Newtonsoft;

namespace Mahasiswa.WP
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            LongListSelector_Main_DataBind();
            GetDataMahasiswa();
            // Set the data context of the LongListSelector control to the sample data
            //DataContext = App.ViewModel;

            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
        }
        public void GetDataMahasiswa()
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://169.254.80.80/akademik/");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = client.GetAsync("api/Mahasiswa").Result;
            if (response.IsSuccessStatusCode)
            {
                MessageBox.Show("Berhasil");
            }
            else
            {
                MessageBox.Show("Gagal");
            }
        }
        public async Task<List<MahasiswaModel>> GetMahasiswa()
        {
            List<MahasiswaModel> mhs = new List<MahasiswaModel>();

            var client = new HttpClient();
            HttpResponseMessage response = await client.GetAsync("http://169.254.80.80/akademik/api/Mahasiswa");
            if (response.IsSuccessStatusCode)
            {
                mhs = response.Content.ReadAsAsync<IEnumerable<MahasiswaModel>>().Result.ToList();
            }

            return mhs;
        }
        protected void LongListSelector_Main_DataBind()
        {
            List<MahasiswaModel> items = new List<MahasiswaModel>();

            WebClient client = new WebClient();
            client.DownloadStringAsync(new System.Uri("http://169.254.80.80/akademik/api/Mahasiswa"));
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);

            //LongListSelector_Main.ItemsSource = items;
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                MessageBox.Show(e.Result);  
                
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        // Load data for the ViewModel Items
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //RunAsync().Wait();
            //if (!App.ViewModel.IsDataLoaded)
            //{
            //    App.ViewModel.LoadData();
            //}
            //List<Test> testCollection = new List<Test>();

            //Test t1 = new Test();
            //t1.att1 = "satu 1";
            //t1.att2 = "satu 2";
            //testCollection.Add(t1);

            //Test t2 = new Test();
            //t2.att1 = "dua 1";
            //t2.att2 = "dua 2";
            //testCollection.Add(t2);

            //MainLongListSelector.ItemsSource = testCollection;
            //MainLongListSelector.b
        }

        public async Task RunAsync()
        {
            List<MahasiswaModel> items = new List<MahasiswaModel>();
            string serviceUrl = "api/Mahasiswa/";

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://169.254.80.80/akademik/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                
                // Menampilkan data mahasiswa
                HttpResponseMessage response = await client.GetAsync(serviceUrl);
                if (response.IsSuccessStatusCode)
                {
                    var data = response.Content.ReadAsAsync<IEnumerable<MahasiswaModel>>().Result;
                    foreach (MahasiswaModel m in data)
                    {
                        items.Add(m);
                    }
                }
            }

            LongListSelector_Main.ItemsSource = items;
        }

        // Handle selection changed on LongListSelector
        private void LongListSelector_Main_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // If selected item is null (no selection) do nothing
            if (LongListSelector_Main.SelectedItem == null)
                return;

            // Navigate to the new page
            NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItem=" + (LongListSelector_Main.SelectedItem as ItemViewModel).ID, UriKind.Relative));

            // Reset selected item to null (no selection)
            LongListSelector_Main.SelectedItem = null;
        }

        // Sample code for building a localized ApplicationBar
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Set the page's ApplicationBar to a new instance of ApplicationBar.
        //    ApplicationBar = new ApplicationBar();

        //    // Create a new button and set the text value to the localized string from AppResources.
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // Create a new menu item with the localized string from AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}
    }

    public class Test
    {
        public string att1 { set; get; }
        public string att2 { set; get; }
    }
}